﻿
//on show button click
function showData() {
    //debugger;

    if ($("#drp_dimesion option:selected").val() == "") {
        alert("Please Select Dimension !");
        return false;
    }
    else {
       
        dimtable_name = $("#drp_dimesion option:selected").data("TableName");
        list_id = $("#drp_dimesion").val();
        var list_name = $("#drp_dimesion option:selected").text();

        var value;
        var jsonstring = "";
        $(".rptInput:checked").each(function () {

            if ($(this).val() != "") {
                value = " " + $(this).val() + " AND";
                jsonstring = jsonstring + value;
            }
        });

        jsonstring = jsonstring.substring(0, jsonstring.length - 3); // + "'}]";
        var fl_rel = $("#fbox_dataGridRpt");

        var filters_rel = fl_rel.jqFilter('filterData');
        //toSQLString
        var queryRel = fl_rel.jqFilter('toSQLString');

        queryRel = queryRel.split("\"").join("'");

        //alert(queryRel);
        //alert(escape(queryRel));     

        //selected columns
        var strcol = "";
        var strcolforData = "";
        $(".chkInput:checked").each(function () {
            //debugger;
            if ($(this).val() != "") {
                value = " '" + $(this).val() + " ',";
                strcol = strcol + value;
                strcolforData = strcolforData + $(this).val() + ",";
            }
        });

        strcol = strcol.substring(0, strcol.length - 1); //
        strcolforData = strcolforData.substring(0, strcolforData.length - 1); //

        addRptTab(jsonstring, queryRel, list_name, list_id, dimtable_name, strcolforData);

        //debugger;
        //alert(strcol);
        showReportData(jsonstring, queryRel, strcol, strcolforData);

        //    var SelSource = $("input[name='radiogrp_Src']:checked").val();

        //    //    $("input[name='radiogrp_Src']").each(function () { //chkgrp_src//if ($("input[name='optConfirm']:checked").val() == '1') {

        //    //        if ($(this).val() != "") {
        //    //            value = " " + $(this).val() + " AND";
        //    //            Src = Src + value;
        //    //        }
        //    //    });

        //    var Src;
        //    if (SelSource == 'SM' || SelSource == 'S') {
        //        Src = "[{value:";
        //        
        //        $("input[name='chkgrp_src']").each(function () { //chkgrp_src
        //            if ($(this).val() != "") {
        //                value = " " + $(this).val() + " AND";
        //                Src = Src + value;
        //            }
        //        });
        //        Src = Src.substring(0, jsonstring.length - 3) + "}]";
        //    }   

        //debugger;  
    }

}

//filss grid data
function showReportData(jsonstring, queryRel, strcol, strcolforData) {

    //debugger;
    var len = $('#tabsRep').tabs('length') - 1;
    var dttable = "#dtgridRptData" + len;
    var pager = "#pgRptData" + len;

    //var qs = HttpUtility.UrlEncode(queryRel, System.Text.Encoding.Default);

    $.ajax({
        async: true,
        type: 'GET',
        // url: "ReportsCallback.aspx?operation=get_gridColdataRpt&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&SrcString=" + jsonstring + "&queryRel=" + queryRel,
        url: "ReportsCallback.aspx?operation=get_gridColdataRpt&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&strcol=" + strcol,
        data: "",
        dataType: "json",
        success: function (result) {
            //debugger;

            var colN = result.columns, colM = result.colModelList;
            $(dttable).GridUnload(); // destroy the grid saving the table and pager

            jQuery(dttable).jqGrid({
                //url: "ReportsCallback.aspx?operation=get_griddataRpt&dimtable_name=" + dimtable_name + "&list_id=" + list_id,
                url: "ReportsCallback.aspx?operation=get_griddataRpt&dimtable_name=" + dimtable_name + "&list_id=" + list_id + "&SourceQuery=" + jsonstring + "&queryRel=" + escape(queryRel) + "&strcol=" + strcolforData,
                datatype: 'json',
                gridview: true,
                colNames: colN,
                colModel: colM,
                caption: "Report Data",
                editurl: "",
                rowNum: 10,
               // loadonce: true,
                pager: pager,
                sortname: result.primarykey,
                sortorder: "asc",
                //width: "100%",
                width: "920px",
                height: "100%",
                scrollOffset: 18,
                closeAfterEdit: true,
                ignoreCase: true,
                viewrecords: true,
                // grouping: true,
                // groupingView: { groupField: ['contact id'],
                //  groupText: ['<b>{0} - {1} Item(s)</b>'] },
                loadComplete: function (data) {
                    //debugger;
                    jQuery(dttable).hideCol(result.primarykey);
                    jQuery(dttable).setGridWidth("850", true);
                    colorGrid(dttable);
                },
                gridComplete: function () {
                   // alert("grid complete fired!!!!");
                },
                loadError: function (xhr, status, error) {
                   // debugger;
                    alert('error');
                    // alert("Source Table Doesn't Exists!");
                }
            });

            // //debugger;
            jQuery(dttable).jqGrid('navGrid', pager,
            { edit: false, add: false, del: false },
            {},
            {},
            {},
            { multipleSearch: true, multipleGroup: false }
            );


        },
        error: function (x, e) {
            //debugger;
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

//change background color depending 
// on source
function colorGrid(dttable) {

    debugger;
    var obj = dttable + " tr td::nth-child(2)";
    $(obj).each(function () {
        if ($(this).html() == "" || $(this).html() == null) {
            //$(this).parent().css("background", "#faf1a5"); //#faf1a5 FFEC8B //#fbfebb
            $(this).parent().addClass("golden");
        }
    });

    //var objcrm = dttable + ' tr td:nth-child(2)[title="CRM"]';
    var objcrm = dttable + ' tr td:[aria-describedby*="_SOURCE"][title="CRM"]';  // [aria-describedby*='_MANUAL_RULE_ID']

    $(objcrm).parent().addClass("crm");

//    $(objcrm).each(function () {
//        //debugger;
//       // $(this).parent().css("background", "#ebfeeb");
//        $(this).parent().addClass("crm");
//    });

    //var objerp = dttable + ' tr td:nth-child(2)[title="ERP"]';
    var objerp = dttable + ' tr td:[aria-describedby*="_SOURCE"][title="ERP"]'; 

    $(objerp).parent().addClass("erp");

//    $(objerp).each(function () {
//        //debugger;
//       // $(this).parent().css("background", "#ffebfe");
//        $(this).parent().addClass("erp");
//    });

    //var objweb = dttable + ' tr td:nth-child(2)[title="WEB"]';
    var objweb = dttable + ' tr td:[aria-describedby*="_SOURCE"][title="WEB"]'; 

    $(objweb).parent().addClass("web");

//    $(objweb).each(function () {
//        //debugger;
//       // $(this).parent().css("background", "#eae9e6");
//        $(this).parent().addClass("web");
//    });
}

//hidden jqgrid for search tool
function loadGridRptdata(dimtable_name, list_id) {
    // debugger;
    //close search dialog            
    //$("a.ui-jqdialog-titlebar-close").click();

    $.ajax({
        async: true,
        type: 'GET',
        url: "ReportsCallback.aspx?operation=get_gridColdata&dimtable_name=" + dimtable_name + "&list_id=" + list_id,
        data: "",
        dataType: "json",
        success: function (result) {
            //debugger;
            var colN = result.columns, colM = result.colModelList;
            var editurl = "";

            makeChkCol(colN, colM, result.columns.length);

            $("#dataGridRpt").GridUnload(); // destroy the grid saving the table and pager

            var pSearch =
            {
                drag: true,
                multipleSearch: true,
                multipleGroup: false,
                showQuery: true,
                showRel: false,
                overlay: false,
                modal: false,
                resetFilterAllRows: true,
                left: 489,
                top: -113
            };

            jQuery("#dataGridRpt").jqGrid({
                data: "",
                datatype: 'local',
                colNames: colN,
                colModel: colM,
                width: "10px",
                ignoreCase: true,
                loadComplete: function (data) {
                    //debugger;

                    jQuery("#dataGridRpt").hideCol(result.primarykey);
                    jQuery("#dataGridRpt").setGridWidth(620, true);
                    $("#gview_" + "dataGridRpt").hide(); //pg_pager
                    $('#gbox_' + "dataGridRpt").removeClass('ui-widget-content');

                    $("#dataGridRpt").jqGrid("searchGrid", pSearch);
                    var fl = $("#fbox_dataGridRpt");  //fbox_dtgridACCT_rule
                    $("input.delete-rule", fl).click();


                    $("#fbox_dataGridRpt_search").hide();
                    $("#fbox_dataGridRpt_query").hide();
                },
                loadError: function (xhr, status, error) {
                    //debugger;   
                    alert(x.readyState + " " + x.status + " " + e.msg);
                }
            });
            // //debugger;
            jQuery("#dataGridRpt").jqGrid('navGrid', '#pagerRpt', { edit: false, add: false, del: false, search: true });


        },
        error: function (x, e) {
            //debugger;
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });

}

//selected columns from checklistbox
function makeChkCol(colN, colM, collength) {

    $("#chkCol").empty();
    var strOptions = '<table cellpadding="0" cellspacing="0" border="0" class="report_table" style="margin-top:20px">';
    strOptions = strOptions + '<tr><td><input type="checkbox" name="chk_all" value="chk_all" checked /><span> Select All</span></td><td></td></tr>';
    //<input type="checkbox" name="chk_all" value="chk_all" checked /><span> Select All</span>

    //debugger;
    $.each(colN, function (i, elm) {
        //debugger;
        if (colM[i].hidden == false && colM[i].key == false) {
            if (i % 2 == 0) {
                strOptions = strOptions + "<tr><td>";
            } else
            { strOptions = strOptions + "<td>"; }

            strOptions = strOptions + '<input type="checkbox" class="chkInput" name="chkgrp_col" value=' + colM[i].index + ' checked /><span>' + elm + '</span>';
            if (i % 2 == 0) {
               
                if (i == (collength - 1)) {                   
                    strOptions = strOptions + "</td><td></td>";
                } else { strOptions = strOptions + "</td>"; }

            } else {               
                strOptions = strOptions + "</td></tr>";
            }
        }
    });

    strOptions = strOptions + "</table>";
    $("#chkCol").append(strOptions);

    $('input[name=chk_all]').attr('checked', true);

    //bind checked event run-time for Select all
    $("input[name='chk_all']").change(function () {
        //debugger;
        if ($(this).is(':checked') == true) {
            $('.chkInput').each(function () { this.checked = true; });
        } else {
            $('.chkInput').each(function () { this.checked = false; });
        }
        // debugger;
    });

}



//add report tab dynamically
function addRptTab(jsonstring, queryRel, list_name, list_id, dimTableName, strcolforData) {

    //debugger;
    var len = $('#tabsRep').tabs('length');
    //$("#tabsRep").tabs("add", "#tabsRep-" + (len), list_name + "-" + "Report" + (len));
    $("#tabsRep").tabs("add", "#tabsRep-" + (len), list_name + "-" + (len));

    var query = jsonstring;
    if (queryRel != "") {
        query = query + " AND " + queryRel;
    }

    var arr = [len];
    var obj = [
      {
          index: len,
          listname: list_name,
          query: query,
          SourceQuery: jsonstring,
          queryRel: queryRel,
          list_id: list_id,
          dimTableName: dimTableName,
          strcolforData: strcolforData
      }
      ];

    $("#tmplDynRpt").tmpl(obj).appendTo("#tabsRep-" + (len));

    //select new tab
    $("#tabsRep").tabs("select", len)

    //css of dimension tab (to make a class and apply)
    $("#tabsRep-" + (len)).css("align", "center");
    $("#tabsDimm-" + (len)).addClass("tabsRep");
}

//export to excel
function export_excel(list_id, SourceQuery, queryRel, dimTableName, strcolforData) {

    var url = "ReportsCallback.aspx?operation=export_excel&dimtable_name=" + dimTableName + "&list_id=" + list_id + "&sord=desc&SourceQuery=" + SourceQuery + "&queryRel=" + queryRel + "&selectedColumns=" + strcolforData;
    window.location = url;
}

//export to pdf
function export_pdf(list_id, SourceQuery, queryRel, dimTableName, strcolforData) {
   // debugger;
    var url = "ReportsCallback.aspx?operation=export_pdf&dimtable_name=" + dimTableName + "&list_id=" + list_id + "&sord=desc&SourceQuery=" + SourceQuery + "&queryRel=" + queryRel + "&selectedColumns=" + strcolforData;
    window.location = url;

}